package com.dkd.day20250619;

import com.dkd.day20250616.TreeNode;

import java.util.Arrays;

public class SolutionreConstructBinaryTree {
    public static void main(String[] args) {

    }

    public TreeNode reConstructBinaryTree (int[] preOrder, int[] vinOrder) {
        // write code here
        int n = preOrder.length;
        int m = vinOrder.length;
        //每个遍历都不能为0
        if (n == 0 || m == 0) {
            return null;
        }
        TreeNode root = new TreeNode(preOrder[0]);
        for (int i = 0; i < vinOrder.length; i++) {
            //找到中序遍历中的前序第一个元素
            if (preOrder[0] == vinOrder[i]) {
                //构建左子树
                root.left = reConstructBinaryTree(Arrays.copyOfRange(preOrder, 1, i + 1),
                        Arrays.copyOfRange(vinOrder, 0, i));
                //构建右子树
                root.right = reConstructBinaryTree(Arrays.copyOfRange(preOrder, i + 1, preOrder.length),
                        Arrays.copyOfRange(vinOrder, i + 1, vinOrder.length));
                break;
            }
        }
        return root;
    }
}
